/**
 * Created by lvzj on 2015/6/16.
 */
var toolUtil = require('../../common/utils/toolUtil');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var users = mongoose.model('user');
var replyAtService = mongoose.model('question_replyAtService');
var async = require('async');
var replyAt = mongoose.model('question_replyAt');
var NeighbourActivity = mongoose.model('activity_neighbour');
var Question = mongoose.model('question');
var SpecialTopics = mongoose.model('system_specialTopics');
var session = require('express-session');
var Community = mongoose.model('community');

exports.getAtCsList = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var communityId = input.communityId;
    var status = input.status;

    var condition = {};

    if (communityId != null && communityId != '') {
        condition.community = communityId;
    }
    if (status != null) {
        condition.status = status;
    }


    async.series([

        function (callbackInner) {
            replyAtService.find(condition).skip(offset).limit(pageSize).populate('atUser', 'nickName').populate('community', 'communityName')
                .sort('-dateCreated').exec(function (err, result) {
                    if (result != null) {
                        async.each(result, function (temp, callbackInner) {
                            replyAt.findOne({replyId: temp._doc.replyId + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (u, i) {
                                        if (temp._doc.content != null)
                                            temp._doc.content = temp._doc.content.replace(new RegExp("@\\{" + i + "\\}"), '@' + u.nickName + ' ')
                                    });
                                }
                                callbackInner();
                            }).populate('uList', '_id nickName');
                        }, function (err) {
                            callbackInner(err, result);
                        })
                    } else {
                        callbackInner(err, result);
                    }
                });
        },
        function (callbackInner) {
            replyAtService.count(condition, function (err, result) {
                var totalPage = 0;
                if (result != null) {
                    var count = result;
                    var totalPage = Math.ceil(count / pageSize);
                }
                callbackInner(err, totalPage);
            });
        }
    ], callback)

};

exports.updateAtCsUpdate = function (input, callback) {

    var id = input.id;

    replyAtService.update({'_id': id}, {'status': false}, callback);

};

exports.getSharedFeeds = function (contentId, category, userId, callback) {

    //Community.find({}).exec(function (err, result) {
    //
    //
    //    var arry = {};
    //    async.each(result, function(item, callback){
    //        arry[item.id] = item;
    //        callback();
    //    }), function(err) {
    //
    //    };



        var typeName = {
            qst: "question",
            act: "neighbourActivity",
            top: "topic"

        }
        var atFlag = '@';
        switch (category) {
            case typeName.qst:
                exports.getQuestion(contentId, function (err, qstObj) {
                    if (err) {
                        callback(err, null);
                    }
                    qstObj._doc['type'] = 1;
                    qstObj._doc['categoryName'] = questionCategory[qstObj.category];
                    qstObj._doc['titleDesc'] = '小区邻居发起的';
                    qstObj._doc['replyCount'] = qstObj.replies.length;
                    qstObj._doc['dateCreated'] = qstObj.dateCreated.getTime();
                    qstObj._doc.createdBy._doc.images = qstObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? qstObj.createdBy.images[0].imageURL : fastDfsHostIp + qstObj.createdBy.images[0].imageURL;

                    var replies = [];
                    if (qstObj.replies != null && qstObj.replies.length > 0) {
                        replies = qstObj.replies;
                    }
                    var data = [];
                    async.eachSeries(replies, function (temp, callbackInner) {
                        if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                            replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (user, i) {
                                        temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                    });
                                }
                                //logger.debug(arry[temp.repliedBy.community]);
                                //logger.debug(temp.repliedBy.nickName);
                                var communityName = '';
                                //if(temp.repliedBy.nickName !='小6客服' ){
                                //    communityName = arry[temp.repliedBy.community]['communityName'];
                                //}

                                logger.debug(temp.repliedBy);
                                var a = {
                                    objId: temp.repliedBy._id,
                                    nickName: temp.repliedBy.nickName,
                                    communityName : communityName,
                                    images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                    replyDesc: temp.replyDesc,
                                    replyDate: temp.dateReplied.getTime()
                                };
                                data.push(a);
                                callbackInner()
                            }).populate('uList', '_id nickName');
                        } else if (temp.replyDesc != null && temp.replyDesc != '') {

                            var communityName = '';
                            //if(temp.repliedBy.nickName !='小6客服' ){
                            //    communityName = arry[temp.repliedBy.community]['communityName'];
                            //}

                            var a = {
                                objId: temp.repliedBy._id,
                                nickName: temp.repliedBy.nickName,
                                communityName : communityName,
                                images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                replyDesc: temp.replyDesc,
                                replyDate: temp.dateReplied.getTime()
                            };
                            data.push(a);
                            callbackInner(err);
                        } else {
                            callbackInner()
                        }
                    }, function (err) {
                        qstObj._doc['replies'] = data;

                        callback(null, {obj: qstObj, "host": fastDfsHostIp});
                    });
                });
                break;
            case typeName.act:
                exports.getNeighbourActivity(contentId, function (err, actObj) {
                    actObj._doc['type'] = 2;
                    actObj._doc['categoryName'] = '邻里活动';
                    actObj._doc['titleDesc'] = '小区邻居发起的';

                    actObj._doc['dateCreated'] = actObj.dateCreated.getTime();
                    if (actObj.deadline != null)
                        actObj._doc.deadline = actObj._doc.deadline.getTime();
                    actObj._doc['replyCount'] = actObj.replies.length;
                    actObj._doc.createdBy._doc.images = actObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? actObj.createdBy.images[0].imageURL : fastDfsHostIp + actObj.createdBy.images[0].imageURL;

                    var replies = [];
                    if (actObj.replies != null && actObj.replies.length > 0) {
                        replies = actObj.replies
                    }
                    var data = [];

                    async.eachSeries(replies, function (temp, callbackInner) {

                        if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                            replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (user, i) {
                                        temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                    });
                                }
                                var communityName = '';
                                if(temp.repliedBy.nickName !='小6客服' ){
                                    communityName = arry[temp.repliedBy.community]['communityName'];
                                }

                                var a = {
                                    objId: temp.repliedBy._id,
                                    nickName: temp.repliedBy.nickName,
                                    communityName : communityName,
                                    images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                    replyDesc: temp.replyDesc,
                                    replyDate: temp.dateReplied.getTime()
                                };
                                data.push(a);
                                callbackInner()
                            }).populate('uList', '_id nickName');
                        } else if (temp.replyDesc != null && temp.replyDesc != '') {
                            var communityName = '';
                            if(temp.repliedBy.nickName !='小6客服' ){
                                communityName = arry[temp.repliedBy.community]['communityName'];
                            }
                            var a = {
                                objId: temp.repliedBy._id,
                                nickName: temp.repliedBy.nickName,
                                communityName : communityName,
                                images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : fastDfsHostIp + temp.repliedBy.images[0].imageURL,
                                replyDesc: temp.replyDesc,
                                replyDate: temp.dateReplied.getTime()
                            };
                            data.push(a);
                            callbackInner(err);
                        } else {
                            callbackInner()
                        }
                    }, function (err) {
                        actObj._doc['replies'] = data;

                        var number = 0;
                        actObj.partake.forEach(function (par) {
                            number += par.number;
                        });

                        actObj._doc['number'] = number;
                        var array = actObj.partake;

                        actObj._doc['partakeNum'] = actObj.partake.length;
                        var partake = [];
                        array.forEach(function (temp) {

                            if (temp.partakeType == 2) {
                                temp._doc.user = {
                                    nickName: temp.name,
                                    images: [{imageURL: wechatImage}]
                                }
                            }
                            var b = {
                                _id: temp.user._id,
                                nickName: temp.user.nickName,
                                images: temp.user.images[0].imageURL.indexOf('http') == 0 ? temp.user.images[0].imageURL : fastDfsHostIp + temp.user.images[0].imageURL,
                                number: temp.number,
                                date: temp.time.getTime()
                            };
                            partake.push(b);
                        });

                        actObj._doc['partake'] = partake;
                        callback(null, {obj: actObj, "host": fastDfsHostIp});
                    });
                });
                break;
            case typeName.top:
                exports.getSpecialTopic(contentId, function (err, topObj) {
                    topObj._doc['type'] = 3;
                    topObj._doc['categoryName'] = '专题';
                    topObj._doc['titleDesc'] = '推荐的有趣';
                    topObj._doc['dateCreated'] = topObj.dateCreated.getTime();


                    var comments = [];
                    if (topObj.comments != null && topObj.comments.length > 0) {
                        comments = topObj.comments;
                    }
                    var data = [];
                    async.eachSeries(comments, function (temp, callbackInner) {

                        if (temp.commentDesc != null && temp.commentDesc.indexOf(atFlag) != -1) {

                            replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (user, i) {
                                        temp.commentDesc = temp.commentDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                    });
                                }
                                //logger.debug(arry[temp.commentedBy.community]);
                                //logger.debug(temp.commentedBy.nickName);
                                var communityName = '';
                                if(temp.commentedBy.nickName !='小6客服' ){
                                    communityName = arry[temp.commentedBy.community]['communityName'];
                                }
                                var a = {
                                    nickName: temp.commentedBy.nickName,
                                    communityName : communityName,
                                    images: temp.commentedBy.images[0].imageURL.indexOf('http') == 0 ? temp.commentedBy.images[0].imageURL : fastDfsHostIp + temp.commentedBy.images[0].imageURL,
                                    replyDesc: temp.commentDesc,
                                    replyDate: temp.commentedDate.getTime()
                                };
                                data.push(a);
                                callbackInner()
                            }).populate('uList', '_id nickName');


                        }else if (temp.commentDesc != null && temp.commentDesc != '') {

                            var communityName = '';
                            if(temp.commentedBy.nickName !='小6客服' ){
                                communityName = arry[temp.commentedBy.community]['communityName'];
                            }
                            var a = {
                                nickName: temp.commentedBy.nickName,
                                communityName : communityName,
                                images: temp.commentedBy.images[0].imageURL.indexOf('http') == 0 ? temp.commentedBy.images[0].imageURL : fastDfsHostIp + temp.commentedBy.images[0].imageURL,
                                replyDesc: temp.commentDesc,
                                replyDate: temp.commentedDate.getTime()
                            };
                            data.push(a);
                            callbackInner(err);
                        }else {
                            callbackInner()
                        }

                    }, function (err) {
                        topObj._doc['replies'] = data;

                        callback(null, {obj: topObj, "host": fastDfsHostIp});
                    });

                });
                break;
        };

    //});
}

exports.getNeighbourActivity = function (activityId, callback) {
    NeighbourActivity.findOne({_id: activityId}, 'title desc category images replies partake browserCount community dateCreated createdBy activityType deadline', callback).populate("community", "communityName").populate('replies.repliedBy', 'community nickName images').populate('partake.user', 'community nickName images').populate('createdBy', 'community nickName images')
}

exports.getQuestion = function (questionId, callback) {
    Question.findOne({_id: questionId}, 'desc category images replies browserCount community dateCreated createdBy', callback).populate("community", "communityName").populate('replies.repliedBy', 'community nickName images').populate('createdBy', 'community nickName images')
}

exports.getSpecialTopic = function (topicId, callback) {
    SpecialTopics.findOne({_id: topicId}, callback).populate('comments.commentedBy', 'community nickName images');
}